//
//  ViewController.m
//  Photoshop
//
//  Created by 鑫龙 on 16/4/13.
//  Copyright © 2016年 鑫龙. All rights reserved.
//

#import "ViewController.h"
#import "DrawingBoardView.h"

#import <CoreBluetooth/CoreBluetooth.h>

#define kCharacteristicUUID @"CEB88D44-1DE0-4B09-A17D-A2BF9DC7B815"
#define kCharacteristicUUIDCentralWr @"CEB88D44-1DE0-4B09-A17D-A2BF9DC7B816"
#define kServiceUUID @"F37B9988-B5B6-42D9-BC88-A15672743070"

//1. 启动蓝牙设备
//1.1 声明一个中央设备管理器属性
//1.2 实例化中央设备管理器对象

//2. 如果成功启动蓝牙设备，开始扫描外设(本质扫描包含某服务(数组)的外设)
//3. 如果成功扫描出服务后，停止扫描并连接外设
//4. 如果成功连接到外设，设置外设delegate对象且用外设去发现服务[这里注意是用外设去发现]
//5. 之后用到的是外设的delegate方法。这样才能获取到外设的服务和特征
//6. 如果成功发现外设服务，获取所需的服务并发现服务里的特征
//7. 如果成功发现特征，获取所需特征。若某特征是广播的，要订阅该特征 (即设置接收特征值改变的通知,YES)
//8. 如果订阅特征成功，表明已经开启监听特征值状态改变的通知
//9. 以后当外设特征值改变时，会通知中央设备，在代理方法中didUpdateValueForCharacteristic:

@interface ViewController ()<CBCentralManagerDelegate,CBPeripheralDelegate>

//1.1 声明一个中央设备管理器属性
@property (nonatomic,strong)CBCentralManager * centralManger;

@property (nonnull,strong)CBPeripheral * peripheral;
@property (nonatomic,strong)CBCharacteristic *characteristic;
@property (nonatomic,strong)DrawingBoardView * dbV;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.dbV = [[DrawingBoardView alloc] initWithFrame:CGRectMake(0, 0, 400, 600)];
    self.dbV.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.dbV];
    
    
    //1.2 实例化中央设备管理器对象
    //参数1 ： delegate
    //参数2 ： 在哪个队列调用回调，nil
    self.centralManger = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
    
    
    //测试中央设备发送数据给外设
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
            if (self.characteristic !=nil) {
                NSString *str = @"hahhaha------aaaaaaa";
                NSLog(@"%@",str);
                NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
                [self.peripheral writeValue:data forCharacteristic:self.characteristic type:CBCharacteristicWriteWithResponse];
            }
        }];
    });
}

//2. 如果成功启动蓝牙设备，开始扫描外设
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    if (central.state == CBCentralManagerStatePoweredOn) {
        NSLog(@"成功接通蓝牙电源");
        
        //扫描外设
        //参数1 ： 数组<CBUUID> 扫描的外设必须包含哪些服务
        //参数2 ： 字典，扫描时的设定CBCentralManagerScanOptionAllowDuplicatesKey,允许重复扫描
        [self.centralManger scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:kServiceUUID]] options:@{CBCentralManagerScanOptionAllowDuplicatesKey : @YES}];
    }
    else {
        NSLog(@"接通蓝牙电源失败");
    }
}

//3.如果搜索到外设回调
//参数1 ： 哪个一个中心设备管理器扫描到了外设
//参数2 ： CBPeripheral一个被扫描的外设
//参数3 : 扫描到的外设在广播时发送的数据
    //NSDictionary * advertisingDict = @{CBAdvertisementDataLocalNameKey:@"handWritingBoard",CBAdvertisementDataServiceUUIDsKey:@[[CBUUID UUIDWithString:kServiceUUID]]};
    //
    //[self.peripheralManager startAdvertising:advertisingDict];
//参数4 ： 信号强度，？（可以根据信号强度确定设备的距离）
           //可以定一个策略，为了保持数据稳定，当信号足够强时才连接
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI {
   
    NSLog(@"成功扫描到外设");
    
    NSArray * uuids = [advertisementData objectForKey:CBAdvertisementDataServiceUUIDsKey];
    for (CBUUID * uuid in uuids) {
        if ([uuid isEqual:[CBUUID UUIDWithString:kServiceUUID]]) {
            //停止扫描外设
            [self.centralManger stopScan];
            
            //返现外设后，外设对象如果没有强引用的执政指向它，会被释放
            self.peripheral = peripheral;
            
            NSLog(@"停止扫描外设");
            //3.1 连接到外设
            //开始连接外设******
            [self.centralManger connectPeripheral:peripheral options:nil];
        }
    }
}

//补充by Cai. 蓝牙断开回调
-(void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
    NSLog(@"didDisconnectPeripheral:%@--error:%@",peripheral,error);
}

//4 如果成功连接到外设回调
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
    
    NSLog(@"成功连接到外设");
    
    peripheral.delegate = self;
    //发现外设的服务
    //参数 需要被发现的服务的UUID 的数组
    [peripheral discoverServices:@[[CBUUID UUIDWithString:kServiceUUID]]];
}

//4.1 如果连接失败
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(nonnull CBPeripheral *)peripheral error:(nullable NSError *)error {
    
    NSLog(@"连接外设失败");
}

#pragma mark - CBPeripheralDelegate
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {
    
    if (!error) {
        NSLog(@"成功发现外设的服务");
        
        //如何发现服务里的特征？
        //1 比例外设的服务,找到服务的UUID与我们想要关注的服务的UUID相同
        //2 发现找到的服务里的特征
        
        //遍历外设中的服务
        for (CBService * servcie in peripheral.services) {
            
            if ([servcie.UUID isEqual:[CBUUID UUIDWithString:kServiceUUID]]) {
                //发现服务里面的特征
                [peripheral discoverCharacteristics:@[[CBUUID UUIDWithString:kCharacteristicUUID], [CBUUID UUIDWithString:kCharacteristicUUIDCentralWr]] forService:servcie];
            }
        }
        
    }else {
        
        NSLog(@"发现外设的服务失败");
    }
}

//如果发现特征成功
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {
    if (!error) {
        NSLog(@"成功发现特征");
        
        //遍历服务里面的所有特征，如找到UUID与我们关注的特征的UUID相同，开启它的通知
        for (CBCharacteristic * characterisc in service.characteristics) {
            if ([characterisc.UUID isEqual:[CBUUID UUIDWithString:kCharacteristicUUID]]) {
                //接收特征的通知
                //外设对象，让外设的特征改变时，发送通知
                //参数1 ： 是否发通知
                //参数2 ： 让哪一个特征发通知
                [peripheral setNotifyValue:YES forCharacteristic:characterisc];
                self.characteristic = characterisc;
            }else if ([characterisc.UUID isEqual:[CBUUID UUIDWithString:kCharacteristicUUIDCentralWr]]){
                self.characteristic = characterisc;
            }
        }
        
    }
    else {
        NSLog(@"发现特征失败");
    }
}

//如果开启通知成功
- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
 
    //如果有错误，返回
    if (error) {
        NSLog(@"变更特征的通知状态失败");
        return;
    }
    
    //判断特征是否已经开启通知
    if (characteristic.isNotifying) {
        NSLog(@"已经开启特征的通知");
    }
    
}

//当外设改变特征的值，会通知到中央设备，特征的新值
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(nonnull CBCharacteristic *)characteristic error:(nullable NSError *)error {
    if (error) {
        NSLog(@"收到特征值跟新失败");
        return;
    }
    
    //取出外设新值
    NSData * data = characteristic.value;
    
    NSString * string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    [self.dbV addPoint:string];
    
    NSLog(@"%@",string);
    
}


@end
